<template>
	<view class="location-selector">
		<view class="location-mask" v-if="visible" @tap="cancel">
		</view>
		<view class="location-container" :class="{ 'location-show': visible }">
			<!-- 顶部操作栏 -->
			<view class="header">
				<text class="cancel" @tap="cancel">取消</text>
				<text class="title">发起活动</text>
				<text class="confirm" @tap="confirm">确定</text>
			</view>

			<!-- 搜索框 -->
			<view class="search-box">
				<view class="search-input-box">
					<image class="search-icon" src="/static/icons/search.png"></image>
					<input type="text" placeholder="搜索地点" v-model="searchKeyword" @input="debounceSearch" />
				</view>
			</view>

			<!-- 地图容器 -->
			<view class="map-container">
				<map id="locationMap" class="map" :latitude="latitude" :longitude="longitude" :markers="markers"
					scale="14" show-location @tap="onMapTap"></map>
			</view>

			<!-- 地址列表 -->
			<scroll-view class="location-list" scroll-y>
				<view class="location-item" v-for="(item, index) in locationList" :key="index"
					@tap="selectLocation(item)">
					<view class="location-info">
						<text class="location-name">{{ item.name }}</text>
						<text class="location-address">{{ item.address }}</text>
					</view>
					<text class="check-icon" v-if="isLocationSelected(item)">✓</text>
				</view>
				<view class="no-data" v-if="locationList.length === 0">
					<text>附近暂无地点</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'LocationSelector',
		data() {
			return {
				visible: false,
				latitude: 23.13,
				longitude: 113.27,
				searchKeyword: '',
				locationList: [],
				markers: [],
				selectedLocation: null,
				searchTimer: null
			}
		},
		methods: {
			open() {
				this.visible = true
				this.getCurrentLocation()
			},
			close() {
				this.visible = false
				this.searchKeyword = ''
				this.locationList = []
			},
			// 防抖搜索
			debounceSearch() {
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
				}
				this.searchTimer = setTimeout(() => {
					this.searchNearbyLocations()
				}, 500)
			},
			getCurrentLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.latitude = res.latitude
						this.longitude = res.longitude
						this.searchNearbyLocations()
					},
					fail: (err) => {
						console.error('获取位置失败：', err)
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						})
					}
				})
			},
			searchNearbyLocations() {
				const key = '替换成你的腾讯LBS应用的key'
				const keyword = this.searchKeyword.trim()
				const radius = 1000 // 搜索半径，单位：米

				// 构建搜索URL
				let url = `https://apis.map.qq.com/ws/place/v1/search?key=${key}&boundary=nearby(${this.latitude},${this.longitude},${radius})`
				if (keyword) {
					url += `&keyword=${encodeURIComponent(keyword)}`
				}

				uni.request({
					url: url,
					success: (res) => {
						console.log('搜索结果：', res.data)
						if (res.data.status === 0) {
							this.locationList = res.data.data.map(item => ({
								name: item.title,
								address: item.address,
								latitude: item.location.lat,
								longitude: item.location.lng
							}))
							this.updateMarkers()
						} else {
							console.error('搜索失败：', res.data)
							uni.showToast({
								title: '搜索失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('请求失败：', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			updateMarkers() {
				this.markers = this.locationList.map((item, index) => ({
					id: index,
					latitude: item.latitude,
					longitude: item.longitude,
					title: item.name,
					width: 32,
					height: 32
				}))
			},
			selectLocation(location) {
				this.selectedLocation = location
				this.latitude = location.latitude
				this.longitude = location.longitude
				this.updateMarkers()
			},
			onMapTap(e) {
				const {
					latitude,
					longitude
				} = e.detail
				this.getAddressFromLocation(latitude, longitude)
			},
			getAddressFromLocation(latitude, longitude) {
				const key = '替换成你的腾讯LBS应用的key'
				uni.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?key=${key}&location=${latitude},${longitude}`,
					success: (res) => {
						console.log('逆地址解析结果：', res.data)
						if (res.data.status === 0) {
							const result = res.data.result
							this.selectedLocation = {
								name: result.formatted_addresses.recommend,
								address: result.address,
								latitude,
								longitude
							}
							// 更新地图标记
							this.markers = [{
								id: 0,
								latitude,
								longitude,
								title: result.formatted_addresses.recommend,
								width: 32,
								height: 32
							}]
						}
					}
				})
			},
			cancel() {
				this.close()
			},
			confirm() {
				if (this.selectedLocation) {
					this.$emit('select', this.selectedLocation)
				}
				this.close()
			},
			// 判断是否是选中的位置
			isLocationSelected(location) {
				return this.selectedLocation && 
					   this.selectedLocation.latitude === location.latitude && 
					   this.selectedLocation.longitude === location.longitude
			}
		}
	}
</script>

<style lang="scss" scoped>
	.location-selector {
		.location-mask {
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			background: rgba(0, 0, 0, 0.4);
			z-index: 998;
		}

		.location-container {
			position: fixed;
			bottom: -100%;
			left: 0;
			right: 0;
			height: 1000rpx;
			background-color: #fff;
			border-radius: 20rpx 20rpx 0 0;
			z-index: 999;
			transition: all 0.3s ease;

			&.location-show {
				bottom: 0;
			}

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1px solid #eee;

				.cancel {
					color: #666;
				}

				.title {
					font-weight: bold;
				}

				.confirm {
					color: #ff6b6b;
				}
			}

			.search-box {
				padding: 20rpx;

				.search-input-box {
					position: relative;
					display: flex;
					align-items: center;
					background-color: #f5f5f5;
					padding: 20rpx;
					border-radius: 10rpx;

					.search-icon {
						width: 32rpx;
						height: 32rpx;
						margin-right: 10rpx;
					}

					input {
						flex: 1;
						font-size: 28rpx;
					}
				}
			}

			.map-container {
				height: 400rpx;

				.map {
					width: 100%;
					height: 100%;
				}
			}

			.location-list {
				height: 400rpx;

				.location-item {
					padding: 20rpx;
					border-bottom: 1px solid #eee;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.location-info {
						flex: 1;
						
						.location-name {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 10rpx;
							display: block;
						}

						.location-address {
							font-size: 24rpx;
							color: #999;
						}
					}

					.check-icon {
						color: #07C160;
						font-size: 40rpx;
						margin-left: 20rpx;
					}

					&:active {
						background-color: #F8F8F8;
					}
				}

				.no-data {
					padding: 40rpx;
					text-align: center;
					color: #999;
					font-size: 28rpx;
				}
			}
		}
	}
</style>